package com.zyl.Ecs.device.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.yulichang.base.MPJBaseServiceImpl;
import com.zyl.Ecs.common.exception.EcsException;
import com.zyl.Ecs.common.response.ResultCode;
import com.zyl.Ecs.common.utils.ObjectUtil;
import com.zyl.Ecs.common.domain.device.bean.Room;
import com.zyl.Ecs.common.domain.device.ext.RoomExt;
import com.zyl.Ecs.device.mapper.RoomMapper;
import com.zyl.Ecs.device.service.RoomService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;


/**
* @version v1.0
* @Package: com.zyl.Ecs.device.service.impl
* @ClassName: RoomServiceImpl
* @Description 针对表【ecs_room】的数据库操作Service实现
* @Author 翟玉龙
* @Date 2024-12-05 09:52:35
*/

@Service
@RequiredArgsConstructor
public class RoomServiceImpl extends MPJBaseServiceImpl<RoomMapper, Room>
    implements RoomService{

    private final RoomMapper roomMapper;

    /**
     * 查询全部机房列表
     *
     * @return {@link List }<{@link RoomExt }>
     * @throws EcsException 异常
     */
    @Override
    public List<RoomExt> getList() throws EcsException {
        return roomMapper.selectList(null)
                .stream()
                .map(RoomExt::toExt)
                .collect(Collectors.toList());
    }

    /**
     * 修改机房信息
     *
     * @param roomExt 机房信息
     * @return {@link RoomExt }
     * @throws EcsException 异常
     */
    @Override
    public RoomExt update(RoomExt roomExt) throws EcsException {
        /* 校验ID是否存在 */
        Integer id = roomExt.getId();
        internalGet(id);

        /* 检查名称是否重复 */
        checkNameUnique(roomExt.getName(), roomExt.getId());

        /* 执行修改 */
        roomExt.setDeleted(0);
        roomMapper.updateById(roomExt);

        return get(id);
    }

    /**
     * 删除机房信息
     * @param id 机房id
     * @return {@link RoomExt }
     */
    private RoomExt get(Integer id) {
        return RoomExt.toExt(internalGet(id));
    }

    /**
     * 根据id获取机房信息
     * @param id 机房id
     * @return {@link Room }
     */
    private Room internalGet(Integer id) {
        Room record = roomMapper.selectById(id);
        if (ObjectUtil.isNull(record)) {
            throw new EcsException(ResultCode.ROOM_NOT_EXIST);
        }
        return record;
    }

    /**
     * 检查名称是否唯一
     * @param name 名称
     * @param id id
     */
    private void checkNameUnique(String name, Integer id) {
        Room record = roomMapper.selectOne(Wrappers.<Room>lambdaQuery()
                .eq(Room::getName, name));
        if (ObjectUtil.nonNull(record) && ObjectUtil.notEquals(record.getId(), id)) {
            throw new EcsException(ResultCode.ROOM_NAME_DUPLICATE);
        }
    }
}




